import Cookie from 'js-cookie' // 导入js-cookie库
import Vue from 'vue' // 导入Vue库
import Vuex from 'vuex' // 导入Vuex库
Vue.use(Vuex) // 使用Vuex插件

// 创建并导出Vuex的Store实例
export default new Vuex.Store({
    state: {
        isCollapse: false, // 侧边栏是否折叠的状态
        token: '', // 用户token
        tabsList: [ // 标签页列表
            {
                path: '/home',
                name: 'home',
                label: '首页',
                icon: 'home'
            }
        ],
        currentMenu: null, // 当前菜单
        menu: [] // 菜单列表
    },
    mutations: {
        collapseMenu(state) { // 改变侧边栏折叠状态的mutation
            state.isCollapse = !state.isCollapse
        },
        selectMenu(state, val) { // 选择菜单的mutation
            state.currentMenu = val
        },
        closeTag(state, val) { // 关闭标签页的mutation
            const result = state.tabsList.findIndex(item => item.name === val.name)
            state.tabsList.splice(result, 1)
        },
        setMenu(state, val) { // 设置菜单的mutation
            state.menu = val
            Cookie.set('menu', JSON.stringify(val))
        },
        clearMenu(state) { // 清空菜单的mutation
            state.menu = []
            Cookie.remove('menu')
        },
        addMenu(state, router) { // 添加菜单的mutation
            const menu = JSON.parse(Cookie.get('menu'))
            state.menu = menu
            const menuArray = menu.flatMap(item => item.children ? item.children : [item])
            menuArray.forEach(item => {
                item.component = () => import(`../components/${item.url}`)
                router.addRoute('MainShow', item)
            })
        },
        setToken(state, val) { // 设置token的mutation
            state.token = val
            Cookie.set('token', val)
        },
        clearToken(state) { // 清空token的mutation
            state.token = ''
            Cookie.remove('token')
        },
        getToken(state) { // 获取token的mutation
            state.token = state.token || Cookie.get('token')
        }
    }
})